package me.numark.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.google.gson.Gson;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import me.numark.NumarkApplication;
import me.numark.R;
import me.numark.model.BaseModel;
import me.numark.model.ConfigResponse;
import me.numark.model.Update;
import me.numark.model.User;
import me.numark.net.NetworkConstants;

/**
 * Created by Evan on 14/11/19.
 */
public class Global {
    public static final int avatarColor = Color.rgb(221,221,221);
    public static final int HAS_READ = 1;
    public static final int NOT_READ = 0;

    public static String BAIDU_USER_ID;
    public static String BAIDU_CHANNEL_ID;

    public static String DeviceUniqueID;

    public static IWXAPI mWxApi;
    public static User currentUser;

    public static File cacheJsonDir;

    public static int currentChatUid;
    public static int currentProfileUid;

    public static String appVersionName;
    public static String appVersionCode;
    public static String osVersion;
    public static String imei;
    public static long currentMaxMid;
    public static BaseModel[] tags;
    public static BaseModel[] hotTags;
    public static Update updateInfo;

    private static final ThreadLocal<Gson> reuseGson = new ThreadLocal<Gson>() {
        @Override
        protected Gson initialValue() {
            return new Gson();
        }
    };

    public static long getCurrentTime(){
        return System.currentTimeMillis();
    }

    public static void appInit(Context context) {
        MobclickAgent.updateOnlineConfig(context);
        PushManager.startWork(context, PushConstants.LOGIN_TYPE_API_KEY, "oCFrxubM4tS8ggIiEoDU2hhc");
        UmengUpdateAgent.update(context);

        mWxApi = WXAPIFactory.createWXAPI(context, Constants.WECHAT_KEY);
        mWxApi.registerApp(Constants.WECHAT_KEY);

        if (Global.DeviceUniqueID == null) {
            Global.DeviceUniqueID = android.provider.Settings.Secure.getString(context.getContentResolver(),
                    android.provider.Settings.Secure.ANDROID_ID);
            if (Global.DeviceUniqueID == null) {
                Global.DeviceUniqueID = String.valueOf(System.currentTimeMillis() % 6000);
            }
        }

        File path = context.getExternalCacheDir();
        cacheJsonDir = new File(path, "json");
        cacheJsonDir.mkdirs();

        currentUser = Settings.getCurrentUser();

        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            appVersionName = info.versionName;
            appVersionCode = String.valueOf(info.versionCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        osVersion = "Android_" + Build.VERSION.SDK_INT;
        imei = Utils.getIMEI(NumarkApplication.getInstance());
        loadConfig(context);
    }

    public static Gson getGson() {
        return reuseGson.get();
    }

    public static int getCurrentUid() {
        if (currentUser != null)
            return currentUser.uid;
        return 0;
    }

    public static boolean isLoggedIn() {
        return getCurrentUid() != 0;
    }

    public static Context getContext() {
        return NumarkApplication.getInstance();
    }

    public static void bindPush() {
        final Map<String, Object> params = new HashMap<String, Object>();
        params.put("bduserid", Global.BAIDU_USER_ID);
        params.put("channelid", Global.BAIDU_CHANNEL_ID);
        params.put("type", "1");
        params.put("imei", imei);
        params.put("uid", String.valueOf(getCurrentUid()));
        new Thread() {
            @Override
            public void run() {
                HttpUtil.get(NetworkConstants.BIND_PUSH_URL, params);
            }
        }.start();
    }

    public static void loadConfig(Context context) {
        String fileName = "config.json";
        final File file = new File(Global.cacheJsonDir, fileName);
        InputStream fis = null;
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            fis = context.getResources().openRawResource(R.raw.config);
        }
        if (fis != null) {
            try {
                BufferedInputStream bis = new BufferedInputStream(fis);
                String data = Utils.readStream(bis);
                ConfigResponse resp = getGson().fromJson(data, ConfigResponse.class);
                tags = resp.data.labels;
                hotTags = resp.data.hot_labels;
                updateInfo = resp.data.update;
            } catch (Exception e) {
            } finally {
                Utils.closeQuietly(fis);
            }
        }
        new Thread() {
            @Override
            public void run() {
                String data = HttpUtil.get(NetworkConstants.GET_CONFIG_URL, null);
                if (data != null) {
                    ConfigResponse resp = getGson().fromJson(data, ConfigResponse.class);
                    if (resp == null) {
                        return;
                    }
                    if (resp.ret) {
                        tags = resp.data.labels;
                        hotTags = resp.data.hot_labels;
                        updateInfo = resp.data.update;
                        FileOutputStream fos = null;
                        try {
                            byte[] bytes = data.getBytes();
                            fos = new FileOutputStream(file);
                            BufferedOutputStream bos = new BufferedOutputStream(fos);
                            bos.write(bytes);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            Utils.closeQuietly(fos);
                        }
                    }
                }
            }
        }.start();
    }
}
